package com.jumi.microservice.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.joda.time.DateTime;


/**
 * JWT token生成和校验工具类
 *
 * @author Administrator
 */
public class JwtUtil {

    private final static String SECRET = "324iu23094u598ndsofhsiufhaf_+0wq-42q421jiosadiusadiasd";

    public static String createToken(long uid, String userName, int expiredDays) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        String token;
        try {
            token = JWT.create()
                    .withIssuer("jumi")
                    .withExpiresAt(DateTime.now().plusDays(expiredDays).toDate())
                    .withClaim("uid", uid)
                    .withClaim("name", userName)
                    .sign(algorithm);
            return token;
        } catch (JWTCreationException e) {
            return null;
        }
    }

    public static DecodedJWT verifyToken(String token) {
        DecodedJWT verify;
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier jwtVerifier = JWT.require(algorithm)
                .withIssuer("jumi")
                .build();
        verify = jwtVerifier.verify(token);
        return verify;
    }
}
